//
//  PublishAirticleViewController.m
//  GolfFriend
//
//  Created by Vescky on 14-2-11.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "PublishAirticleViewController.h"
#import "VKCollectionViewCell.h"
#import "ArticlePreviewViewController.h"
#import "AppsEngine.h"
#import "AppsLocationManager.h"
#import "DXAlertView.h"
#import "SVProgressHUD.h"
#import "UserSession.h"
#import "ImageUploader.h"
#import "CircleContentVO.h"
#import "JSON.h"

#import "CacheDaoForCircleContent.h"
#import "WatermarkCameraViewController.h"

#import <ImageIO/ImageIO.h>
#import <AssetsLibrary/AssetsLibrary.h>

#import "DateUtility.h"
#import "CommonUtility.h"

#import "AppDelegate.h"

@interface PublishAirticleViewController ()<UITableViewDataSource,UITableViewDelegate,VKCollectionViewCellDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITextViewDelegate> {
    NSMutableArray *pcArray,*allCollectionPhotos;//照片选择view数组
    NSMutableArray *selectedPhotos;
    bool located,isNewsPictureSelected;//定位完毕标记
    NSString *detailAddress;
    UIImagePickerController *photoPicker;
}

@end

@implementation PublishAirticleViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.navigationController.navigationBar setHidden:NO];
    [self setTitle:@"发表文章"];
    [super customBackButton];
//    [self.navigationItem setHidesBackButton:YES animated:NO];
//    [self.navigationController.navigationBar setHidden:NO];
    [self initView];
    
    [[APP_DELEGATE photoAlbumSelectedArray] removeAllObjects];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [APP_DELEGATE handleChatMessage:nil];
    //刷新相册
    [self getImgs];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private
- (void)initView {
    CGRect mRect = viewMiddle.frame;
    mRect.origin.y = tvContent.frame.origin.y + tvContent.frame.size.height;
    tvContent.delegate = self;
    
    [viewMiddle setFrame:mRect];
    
    CGRect bRect = viewButtom.frame;
    bRect.origin.y = mRect.origin.y + mRect.size.height;
    bRect.size.height = self.view.frame.size.height - bRect.origin.y;
    [viewButtom setFrame:bRect];
    
//    if (iPhone5) {
//        CGRect tbr = viewButtom.frame;
//        tbr.size.height = 360;
//        viewButtom.frame = tbr;
//    }
    
    //定制自己的风格的  UIBarButtonItem
    UIButton* publishButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 7, 30, 30)];//
    [publishButton setImage:[UIImage imageNamed:@"btn_sure.png"] forState:UIControlStateNormal];
//    [publishButton setImage:[UIImage imageNamed:@"comment_05.png"] forState:UIControlStateHighlighted];
    [publishButton addTarget:self action:@selector(publishArticle) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* actionItem= [[UIBarButtonItem alloc] initWithCustomView:publishButton];
    [self.navigationItem setRightBarButtonItem:actionItem];
    
    //设置可自动换行的label
    [labelLocation setLineBreakMode:0];
    [labelLocation setNumberOfLines:0];
    
    located = NO;
    
    pcArray = [[NSMutableArray alloc] init];
    allCollectionPhotos = [[NSMutableArray alloc] init];
    selectedPhotos = [[NSMutableArray alloc] init];
//    [self test];
//    [self getMyLocation];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getImgs) name:@"PhotoCollectionRefreshed" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectNewsPicture) name:@"selectNewsPicture" object:nil];
}

- (void)test {
    NSArray *arr1 = [[NSArray alloc] initWithObjects:
                     [[NSDictionary alloc] initWithObjectsAndKeys:@"comment_29-1.png",@"imagePath",[NSNumber numberWithInt:1],@"cellUnitType",nil],
                     [[NSDictionary alloc] initWithObjectsAndKeys:@"comment_26.png",@"imagePath",[NSNumber numberWithInt:0],@"cellUnitType",nil],
                     [[NSDictionary alloc] initWithObjectsAndKeys:@"comment_27.png",@"imagePath",[NSNumber numberWithInt:0],@"cellUnitType",nil], nil];
    [pcArray addObject:arr1];
}


- (void)getMyLocation {
    [labelLocation setText:@"定位中..."];
    [lIndicator startAnimating];
    
    CLLocation *currentLocation = [[AppsLocationManager sharedManager] currentLocation];
//#if DEBUG
//    CLLocation *defaultLocation = [[CLLocation alloc] initWithLatitude:23.135727 longitude:113.327367];
//    currentLocation = defaultLocation;
//#endif
    NSString *urlStrinng = [NSString stringWithFormat:@"http://api.map.baidu.com/geocoder/v2/?ak=nLTjxKmjxrMiGBtwVxr5DrL9&output=json&pois=1&location=%lf,%lf",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude];
    
    [[AppsEngine shareAppsEngine] submitSimpleRequest:urlStrinng onCompletion:^(id jsonResponse) {
        [lIndicator stopAnimating];
        if (![[jsonResponse objectForKey:@"status"] integerValue]) {
            //status = 0,请求成功
            located = YES;
            detailAddress = [[jsonResponse objectForKey:@"result"] objectForKey:@"formatted_address"];
            [labelLocation setText:detailAddress];
        }
        else {
            [labelLocation setText:@"定位失败"];
        }
    } onError:^(NSError *error) {
        [lIndicator stopAnimating];
        [labelLocation setText:@"定位失败"];
    } method:@"GET"];
}

- (void)showCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
#pragma mark If water-camera needed,uncommand these lines
//        WatermarkCameraViewController *wVc = [[WatermarkCameraViewController alloc] init];
//        [self.navigationController pushViewController:wVc animated:YES];
//        return;
        
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;  //是否可编辑
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        photoPicker = picker;
        [self presentModalViewController:photoPicker animated:YES];
    }else{
        //如果没有提示用户
        [SVProgressHUD showErrorWithStatus:@"您的设备不支持拍照!"];
    }

}

- (void)selectNewsPicture {
    isNewsPictureSelected = YES;
}

#pragma mark 遍历相册
//遍历相册
-(void)getImgs{
    __block NSMutableArray *dataArray = [[NSMutableArray alloc] init];
        ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){
            NSLog(@"相册访问失败");
            if ([myerror.localizedDescription rangeOfString:@"Global denied access"].location!=NSNotFound) {
                NSLog(@"无法访问相册.请在'设置->定位服务'设置为打开状态.");
            }else{
                NSLog(@"相册访问失败.");
            }
        };
        
        ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result,NSUInteger index, BOOL *stop){
            if (result!=NULL) {
                
                if ([[result valueForProperty:ALAssetPropertyType]isEqualToString:ALAssetTypePhoto]) {
                    
                    NSString *urlstr=[NSString stringWithFormat:@"%@",result.defaultRepresentation.url];//图片的url
                    UIImage *thumbnailImg = [[UIImage alloc] initWithCGImage:result.thumbnail];
                    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:thumbnailImg,@"thumbnail",//UIImage
                                          urlstr,@"imagePath",//NSString
                                          [result valueForProperty:ALAssetPropertyDate],@"date",//NSDate
                                          @0,@"cellUnitType",nil];//NSNumber
                    [dataArray addObject:dict];
                }
            }
            
        };
    
        ALAssetsLibraryGroupsEnumerationResultsBlock libraryGroupsEnumeration = ^(ALAssetsGroup* group,BOOL* stop){
            if (group!=nil) {
                NSString *g=[NSString stringWithFormat:@"%@",group];//获取相簿的组
                NSLog(@"gg:%@",g);//gg:ALAssetsGroup - Name:Camera Roll, Type:Saved Photos, Assets count:71
                //Photo Stream
                NSLog(@"%@",[group valueForProperty:ALAssetsGroupPropertyName]);
                if (![[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:@"My Photo Stream"]) {
                    [group enumerateAssetsUsingBlock:groupEnumerAtion];
                }
            }
            else {
                [pcArray removeAllObjects];
                allCollectionPhotos = [self sortArrayByDate:dataArray];
                if (isNewsPictureSelected) {
                    isNewsPictureSelected = NO;
                    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:[allCollectionPhotos firstObject]];
                    [dict setObject:@1 forKey:@"isSelected"];
                    if (dict) {
                        [allCollectionPhotos replaceObjectAtIndex:0 withObject:dict];
                    }
                    [self VKCollectionViewCellDidPressed:dict];
                }
                pcArray = [self splitArray:allCollectionPhotos];
                NSLog(@"total photos:%d",[dataArray count]);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //tb reload
                    [tbPhotoCollection reloadData];
                });
            }
            
        };
        
        ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
        [library enumerateGroupsWithTypes:ALAssetsGroupAll
                              usingBlock:libraryGroupsEnumeration
                            failureBlock:failureblock];
}

//按照日期将图片数组排序
- (NSMutableArray*)sortArrayByDate:(NSMutableArray*)_arr {
    NSArray *rArr = [_arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDate *date1 = [obj1 objectForKey: @"date"];//getDateFromString(@"yyyy-MM-dd HH:mm:ss", [obj1 objectForKey: @"dateString"]);
        NSDate *date2 = [obj2 objectForKey: @"date"];//getDateFromString(@"yyyy-MM-dd HH:mm:ss", [obj2 objectForKey: @"dateString"]);
        
        if ([date1 isEqualToDate:[date1 laterDate:date2]]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        if ([date2 isEqualToDate:[date1 laterDate:date2]]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    return [[NSMutableArray alloc] initWithArray:rArr];
}

//将数组分成3个一组
- (NSMutableArray*)splitArray:(NSMutableArray*)_arr {
//    if (!_arr || [_arr count] < 1) {
//        NSDictionary *_dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"comment_29-1.png",@"imagePath",@1,@"cellUnitType",nil];
//        return [[NSMutableArray alloc] initWithObjects:[[NSMutableArray alloc] initWithObjects:_dict, nil], nil];
//    }
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < [_arr count];) {
        NSMutableArray *gArr = [[NSMutableArray alloc] init];
//        if (i == 0) {
//            NSDictionary *_dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"comment_29-1.png",@"imagePath",@1,@"cellUnitType",nil];
//            [gArr addObject:_dict];
//        }
       
        if ([_arr objectAtIndex:i]) {
            [gArr addObject:[_arr objectAtIndex:i]];
            i++;
        }
        if (i < [_arr count] && [_arr objectAtIndex:i]) {
            [gArr addObject:[_arr objectAtIndex:i]];
            i++;
        }
        if (i < [_arr count] && [_arr objectAtIndex:i] && [gArr count] < 3) {
            [gArr addObject:[_arr objectAtIndex:i]];
            i++;
        }
        
        [resultArr addObject:gArr];
    }
    
    return resultArr;
}

- (NSString*)getCirclePhotoNameBySuffix:(NSString*)_suffix {
    //circle_[userId]_[date]_[sNo].suffix
    NSString *cLink = [NSString stringWithFormat:@"circle_%@_%@_%@.%@",
                            [[UserSession shareUserSession] getUserId],
                            getStringFromDate(@"yyyyMMddHHmmss", [NSDate date]),
                            getRandomStrings(5),
                            _suffix];
    return cLink;
}


- (void)submitResultToSina:(NSMutableDictionary*)_dict {
    [[AppsEngine shareAppsEngine] submitRequest:@"gfPublishCircleArticle" param:_dict onCompletion:^(id jsonResponse) {
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            NSLog(@"提交成功!");
            [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Article_Published object:nil];
        }
        else {
            NSLog(@"-------------  提交失败!\n reason:%@",[jsonResponse objectForKey:@"reason"]);
        }
    } onError:^(NSError *error) {
        NSLog(@"------------- 无法连接网络!\nreason:%@",error);
    } method:@"GET"];
}

#pragma mark - Button Action
- (void)publishArticle {
    
    NSLog(@"publish action!");
    bool hasText = NO;
    
    if (tvContent.text.length > 0) {
        hasText = YES;
    }
//    if ([selectedPhotos count] > 0) {
//        hasImage = YES;
//    }
    
    if (!hasText) {
        [SVProgressHUD showErrorWithStatus:@"不能发表空内容!!"];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"正在提交..."];
    [self performSelector:@selector(handleSubmittion) withObject:nil afterDelay:0.5];
}

- (void)handleSubmittion {
    bool hasImage = NO;
    if ([selectedPhotos count] > 0) {
        hasImage = YES;
    }
    //准备上传参数 - sina
    NSString *uId = [[UserSession shareUserSession] getUserId];
    if (!uId || uId.length <= 0) {
        uId = @"";
    }
    
    NSMutableDictionary *resultToSubmit = [[NSMutableDictionary alloc] initWithObjectsAndKeys:uId,@"userId",
                                           tvContent.text ,@"content",
                                           (located ? (detailAddress ? detailAddress : @"") : @""),@"location",
                                           @"",@"sources",nil];
    
    NSMutableArray *saveNameList = [[NSMutableArray alloc] init];
    for (int i = 0; i < [selectedPhotos count]; i++) {
        NSString *fName = [NSString stringWithFormat:@"%@/%@",Qiniu_Backet_Domain,[self getCirclePhotoNameBySuffix:@"png"]];
        [saveNameList addObject:fName];
    }
    
    if (saveNameList && [saveNameList count] > 0) {
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"",@"video",saveNameList,@"image", nil];
        [resultToSubmit setObject:[dict JSONFragment] forKey:@"sources"];
    }
    
    if (hasImage) {
//        [self uploadPhotos:saveNameList];//后台上传图片,并提交结果
        [APP_DELEGATE uploadImageWithArray:selectedPhotos saveNameList:saveNameList submitToSinaPaarms:resultToSubmit];
    }
    else {
        //直接提交数据到sina
        [self submitResultToSina:resultToSubmit];
    }
    
//    CircleContentVO *cVo = [[CircleContentVO alloc] init];
//    cVo.articleId = @"99999999";
//    cVo.content = [resultToSubmit objectForKey:@"content"];
//    cVo.userId = [resultToSubmit objectForKey:@"userId"];
//    cVo.userName = [[UserSession  shareUserSession] getUserName];
//    cVo.cityName = [resultToSubmit objectForKey:@"location"];
//    cVo.time = getStringFromDate(@"yyyy-MM-dd HH:mm:ss", [NSDate date]);
//    cVo.clicks = @"0";
//    cVo.comments = @"0";
//    cVo.zan = @"0";
//    cVo.isSupported = @"2";
//    cVo.sourceLinks = [[NSMutableDictionary alloc] initWithObjectsAndKeys:selectedPhotos,@"image",@"",@"video", nil];
//    cVo.avatar = [[UserSession shareUserSession] getUserAvatar];
//    
//    if (!cVo.userName) {
//        cVo.userName = @"佚名";
//    }
//    
//    [[CacheDaoForCircleContent shareCacheDaoForCircleContent] updateCacheDataWithCircleContent:cVo];
//    
//    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Article_Published object:cVo];
    
    if (hasImage) {
        [SVProgressHUD showSuccessWithStatus:@"后台上传图片..."];
    }
    else {
        [SVProgressHUD showSuccessWithStatus:@"发表成功!"];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (IBAction)btnAction:(id)sender {
    UIButton *btn = (UIButton*)sender;
    if (btn.tag == 101) {
        //预览
        [self showCamera];
//        [tvContent resignFirstResponder];
    }
    else if(btn.tag == 102) {
        //定位or取消定位
        if (located) {
            //不显示定位
            located = NO;
            [labelLocation setHidden:YES];
        }
        else {
            //显示定位
            if (detailAddress && detailAddress.length > 0) {
                //有结果，直接显示；无结果，正在定位中 。
                located = YES;
                [labelLocation setHidden:NO];
            }
            else {
                [self getMyLocation];
            }
        }
    }
    else if(btn.tag == 103) {
        //完成编辑
        [tvContent resignFirstResponder];
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [pcArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"VKCollectionViewCell";
    VKCollectionViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
//        cell = [[[NSBundle mainBundle] loadNibNamed:@"VKCollectionViewCell" owner:self options:nil] objectAtIndex:0];
        cell = [[VKCollectionViewCell alloc] init];
    }
    
    cell.delegate = self;
    
    [cell setDataInfo:[pcArray objectAtIndex:indexPath.row]];
    
    [cell setTag:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100.0;
}

#pragma mark - VKCollectionViewCellDelegate
- (void)VKCollectionViewCellDidPressed:(NSDictionary*)_dict {
    
//    if ([selectedPhotos count] >= Max_Article_Photo) {
//        [SVProgressHUD showErrorWithStatus:@"最多可选6张照片"];
//    }
    
    if ([[_dict objectForKey:@"cellUnitType"] integerValue] == PhotoStyle) {
        NSString *unitImagePath = [_dict objectForKey:@"imagePath"];
        if (!unitImagePath || unitImagePath.length < 1) {
            return;
        }
        if ([self isUnitSelected:unitImagePath]) {
            [selectedPhotos removeObject:unitImagePath];
        }
        else {
            [selectedPhotos addObject:unitImagePath];
        }
        [self refreshPcArray];
    }
    else {
        [self showCamera];
    }
}

- (bool)isUnitSelected:(NSString*)imgPath {
    if (!imgPath || imgPath.length < 1) {
        return NO;
    }
    for (int i = 0; i < [selectedPhotos count]; i++) {
        if ([[selectedPhotos objectAtIndex:i] isEqualToString:imgPath]) {
            return YES;
        }
    }
    return NO;
}

- (void)refreshPcArray {
    for (int i = 0; i < [pcArray count]; i++) {
        NSMutableArray *arr = [NSMutableArray arrayWithArray:[pcArray objectAtIndex:i]];
        for (int j = 0; j < [arr count]; j++) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[arr objectAtIndex:j]];
            if ([self isUnitSelected:[dict objectForKey:@"imagePath"]]) {
                [dict setObject:@1 forKey:@"isSelected"];
            }
            [arr replaceObjectAtIndex:j withObject:dict];
        }
        [pcArray replaceObjectAtIndex:i withObject:arr];
    }
}

#pragma mark - UINavigationControllerDelegate,UIImagePickerControllerDelegate
//拍摄完成后要执行的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到图片
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//[self saveAndResizeImage:image asName:@"tmp.png"]
        NSString *savePath = [NSString stringWithFormat:@"GF-Document:%@",saveAndResizeImage(image, @"tmp.png",640)];
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:image,@"thumbnail",//UIImage
                              savePath,@"imagePath",//NSString
                              [NSDate date],@"date",//NSDate
                              @0,@"cellUnitType",//NSNumber
                              @0,@"isSelected",nil];//NSNumber
        [allCollectionPhotos insertObject:dict atIndex:0];
        [pcArray removeAllObjects];
        pcArray = [self splitArray:allCollectionPhotos];
        
//        [selectedPhotos addObject:savePath];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"selectNewsPicture" object:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //tb reload
            [self getImgs];
//            [tbPhotoCollection reloadData];
        });
    });
    
    //图片存入相册
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    [self dismissModalViewControllerAnimated:YES];
}

//点击Cancel按钮后执行方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    textView.inputAccessoryView = viewDoneEditing;
    return YES;
}


@end
